import React, { useState, useMemo, useCallback, useEffect } from 'react'
import { NavBar, Space, Toast, Divider, Button, Modal } from 'antd-mobile'

import { CloseOutline, MoreOutline, SearchOutline } from 'antd-mobile-icons'
import { useLocation, useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
import './style/Consultation_chat.css'
import axios from 'axios';
export default props => {
  const navigate = useNavigate();
  const location = useLocation();
  const box = location.state.item

  const [Patient, SETPatient] = useState([])
  const [chatdata, setchatdata] = useState([])
  const [from, setfrom] = useState({})


  const right = (
    <div style={{ fontSize: 24 }}>
      <button className='end' onClick={() => {
        Modal.show({
          content: '是否结束本次咨询？',
          closeOnAction: true,
          actions: [
            {
              key: 'online',
              text: '确认',
              primary: true,
              onClick:()=>{
                emitDisconnect('wwww')
              }
            },
            {
              key: 'download',
              text: '取消',
            },
          ],
        })
        // 
      }}>结束本次咨询</button>
      <Space style={{ '--gap': '10px', marginLeft: '30px' }}>
        <MoreOutline onClick={() => {
          getuser(),
            navigate('/Video_calls', { state: { from: from } })
        }} />
      </Space>
    </div>
  )

  const back = () =>
    Toast.show({
      content: navigate(-1),
      duration: false,
    })




  // 获取当前病人和医生的信息
  const getuser = async () => {
    const { data: { data, doctor } } = await axios.get(`/DQJ/getchatPatient?_id=${box._id}&doctor_id=${box.doctor_id}`)
    SETPatient(data)
    let from = {
      bingphone: data[0].phone,
      yiphone: doctor[0].phone
    }
    setfrom(from)
  }


  // 获取和医生得聊天信息
  const getchat = async () => {
    let doctor_id = box.doctor_id
    const { data: { data } } = await axios.get(`/DQJ//getchattalk?user_id=${box._id}&doctor_id=${doctor_id}`)
    setchatdata(data)
  }






  const [userCount, setUserCount] = useState(0)
  const [sendMessage, setSendMessage] = useState('');
  const [receiveMessage, setReceiveMessage] = useState([]);

  const socket = useMemo(() => {
    return io('http://localhost:4000', {
      path: '/socket.chat',
      // 默认值为 [ 'polling' ]
      transports: ['websocket']
    });
  }, [])

  useEffect(() => {
    getuser()
    getchat()

    socket.on('connect', () => {
      socket.connected ? console.log('已连接...') : console.error('连接失败');
    });


    socket.on('disconnect', () => {
      socket.disconnected ? console.log('已断开链接...') : console.error('断开失败');
    });

    socket.on('userCount', ({ msg }) => {

      console.log("%s 人在线", msg); // true
      setUserCount(msg)
    });

    socket.on('newMessage', ({ msg }) => {
      setReceiveMessage(state => ([
        ...state,
        msg
      ]))
    });
  },[])




  // 断开链接申请
  const emitDisconnect = useCallback(async (msg) => {

    let from = {
      user_id: box._id,
      doctor_id: box.doctor_id
    }
    let { data: { code } } = await axios.post('/DQJ/postcallstype', from)
    if (code == 200) {
      Toast.show({
        icon: 'success',
        content: '结束聊天成功',
      })
      navigate('/Dqj_My_consultation')
    }

    console.log('提交断开连接申请')
    socket.close();
  }, [socket])



  // 发送消息
  const sendMsg = useCallback(async (msg) => {
    if (msg == '') {
      return
    } else {
      let from = {
        user_id: box._id,
        doctor_id: box.doctor_id,
        content: msg,
        datetime: new Date(),
        msg_type: JSON.parse(sessionStorage.getItem('user')).identity
      }
      console.log(from);
      let { data: { code } } = await axios.post('/DQJ/postchat', from)
      if (code == 200) {
        getchat()
      }
      socket.emit('sendMessage', { data: msg });
    }

  }, [socket])





  return <div className='wrap'>
    {/* 头部 */}
    <div className='title'>
      <NavBar style={{ backgroundColor: 'white' }} right={right} onBack={back}>
        在线咨询
      </NavBar>
      <div className='chatuser'>
        <h2 style={{ paddingTop: '3%', paddingLeft: '3%' }}>病人具体信息</h2>
        <div style={{ marginLeft: '5%' }}>
          {Patient.map(item => {
            return <div key={item._id}>
              <p style={{ marginTop: '3%' }}>病人基础信息:
                <span style={{ fontWeight: "700" }}>{item.nickname}，{item.gender}，{item.age}岁</span>，

              </p>
              <p style={{ marginTop: '3%' }}>病人身高/体重:
                <span style={{ fontWeight: '700' }}>{item.height} / {item.weight}</span>
              </p>
              <p style={{ marginTop: '3%' }}>病人过敏史:
                <span style={{ fontWeight: '700' }}>{item.allergy}</span>
              </p>
              <p style={{ marginTop: '3%' }}>既往病史:
                <span style={{ fontWeight: '700' }}>
                  {item.disease}
                </span>
              </p>
              <p style={{ marginTop: '3%', paddingBottom: '3%' }}>家族病史:
                <span style={{ fontWeight: '700' }}>
                  {item.family}
                </span>
              </p>
            </div>
          })}
        </div>
      </div>
    </div>


    {/* 聊天区域渲染 */}
    <div style={{ marginTop: '67%', paddingBottom: '10%' }}>
      <div className='chatBox'>

        {/* <div>{userCount} 人在线</div> */}
        {/* {receiveMessage.length > 0 && receiveMessage.map(item => <p className='receive' key={String(Date() + Math.random())}>{item.data}</p>)} */}



        {chatdata.map(item => {
          return <div className='msgchat' key={item._id} style={{ textAlign: item.msg_type == JSON.parse(sessionStorage.getItem('user')).identity ? 'right' : 'left' }}>
            <img style={{ display: item.msg_type == false ? 'inline-block' : 'none' }} className={item.identity ? 'rightitemimg' : 'leftitemimg'} src={item.msg_type == true ? "https://ts2.cn.mm.bing.net/th?id=OIP-C.pQeSINEM5g5ei5vcITKpOQAAAA&w=207&h=207&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2" : "https://tse4-mm.cn.bing.net/th/id/OIP-C.rY9ifuLFZzv6PZHw8Av99gAAAA?w=207&h=206&c=7&r=0&o=5&dpr=1.5&pid=1.7"} alt="" />
            <p key={item._id} className='msg'>{item.content}</p>
            <img style={{ display: item.msg_type == true ? 'inline-block' : 'none' }} className={item.identity ? 'rightitemimg' : 'leftitemimg'} src={item.msg_type == true ? "https://ts2.cn.mm.bing.net/th?id=OIP-C.pQeSINEM5g5ei5vcITKpOQAAAA&w=207&h=207&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2" : "https://tse4-mm.cn.bing.net/th/id/OIP-C.rY9ifuLFZzv6PZHw8Av99gAAAA?w=207&h=206&c=7&r=0&o=5&dpr=1.5&pid=1.7"} alt="" />
          </div>
        })}
      </div>
    </div >

    <div className='chatInput'>
      <div className='chatInputMid'>
        <input type="text" className='inputText' value={sendMessage} onChange={(e) => { setSendMessage(e.target.value) }} placeholder="请输入..." />
      </div>
      <button className='chatInputRight' onClick={() => { sendMsg(sendMessage); setSendMessage(''); getchat() }}>发送</button>
    </div>
  </div>
}